package com.leyou.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.upload.config.OSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class UploadService {
    // 支持的文件类型
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg", "image/bmp");

    /**
     * 本地图片上传
     * @param file
     * @return
     */
    public String uploadImage(MultipartFile file) {
//        验证文件媒体格式
        String contentType = file.getContentType();
        if(!suffixes.contains(contentType)){
//            如果上传的文件类型不符合要求
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
//        验证图片流，使用java提供的ImageIO
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if(bufferedImage == null){
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
//        获取源文件的名字
        String originalFilename = file.getOriginalFilename();
//        获取后缀 XXx.jpg 结果 .jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//         创建新的文件名称 UUID + 后缀
        String newFileName = UUID.randomUUID()+suffix;
//        图片需要使用nginx负载，上传nginx的html目录
        String filePath = "C:\\workspace\\heima-jee-tj-2\\nginx-1.12.2\\html";
//        构造本地目录
        File dir = new File(filePath);
        if(!dir.exists()){
//          如果目录不存在,创建
            dir.mkdir();
        }
//        创建新的文件
        File newFile = new File(dir,newFileName);
//        保存图片到本地
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
//        构造图片的url
        String imgUrl = "http://image.leyou.com/"+newFileName;
        return imgUrl;
    }


    @Autowired
    private OSSProperties prop;
    @Autowired
    private OSS client;
    /**
     * 获取签名
     * @return
     */
    public Map<String,Object> signature() {

        try {
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);
            return respMap;
        }catch (Exception e){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

    }
}
